const app = getApp()

Page({

  data: {
    imgWidth: 0,
    imgHeight: 0,
    id: 1,
    imgUrl: '',
    userImg: '',
    userName: '',
    isCollect: false
  },

  onLoad: function(options) {
    wx.hideTabBar();
    var that = this
    var user = JSON.parse(options.user)
    that.setData({
      id: user.id,
      imgUrl: user.imgUrl,
      userImg: user.userImg,
      userName: user.userName
    })
    wx.setNavigationBarTitle({
      title: that.data.userName + '的大作'
    })
    that.checkCollect();
  },

  // onShareAppMessage: function () {
  //   return {
  //     title: '@你,快来欣赏大师之作',
  //     path: '/pages/detail/detail?id=' + this.data.id
  //   }
  // },

  // 保存至相册
  save: function() {
    var that = this
    wx.downloadFile({
      url: that.data.imgUrl, //仅为示例，并非真实的资源
      success: function(res) {
        // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
        if (res.statusCode === 200) {
          // 保存
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: function(res) {
              console.log("保存成功")
            }
          })
        }
      }
    })
  },

  onShareAppMessage: function() {
    return {
      title: '创作属于你的艺术!',
      imageUrl: '/images/share.jpg',
      path: '/pages/index/index'
    }
  },

  previewImg: function(e) {
    var img = this.data.imgUrl
    wx.previewImage({
      current: img,
      urls: [img]
    })
  },

  // 收藏
  collect: function(e) {
    var that = this

    // 加入收藏
    if (!that.data.isCollect) {
      wx.request({
        url: app.globalData.url + 'add_favor',
        data: {
          acc_id: app.globalData.userId,
          favor_id: that.data.id
        },
        method: 'POST',
        success: (result) => {
          if (result.data == 1) {
            that.setData({
              isCollect: true
            })
          }
        }
      });
    } else {
      wx.request({
        url: app.globalData.url + 'del_favor',
        data: {
          acc_id: app.globalData.userId,
          favor_id: that.data.id
        },
        method: 'POST',
        success: (result) => {
          if (result.data == 1) {
            that.setData({
              isCollect: false
            })
          }
        }
      });
    }
  },

  // 检查是否收藏
  checkCollect: function() {
    var that = this
    var id = that.data.id
    wx.request({
      url: app.globalData.url + 'fetch_favor',
      data: {
        acc_id: app.globalData.userId,
        favor_id: id
      },
      method: 'POST',
      success: (result) => {
        var res = result.data.msg
        if (res == 1) {
          that.setData({
            isCollect: true
          })
        } else if (res == 0) {
          that.setData({
            isCollect: false
          })
        }
      }
    });
  }
})